package com.ayuan.blog.service.impl;

import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.durcframework.core.service.CrudService;
import com.ayuan.blog.service.WxUserService;
import com.ayuan.blog.dao.WxUserDao;
import com.ayuan.blog.domain.WxUser;
import com.ayuan.blog.domain.sch.WxUserSch;
import org.springframework.stereotype.Service;

import java.util.List;
    
@Service
public class WxUserServiceImpl 
        extends CrudService<WxUser, WxUserDao> 
        implements WxUserService {

    @Override
    public PageInfo<WxUser> findPage(WxUserSch sch) {
        ExpressionQuery query = new ExpressionQuery();
        query.addPaginationInfo(sch);
        query.addAnnotionExpression(sch);

        long total = this.getDao().findTotalCount(query);
        List<WxUser> list = this.getDao().find(query);

        PageInfo<WxUser> page = new PageInfo<WxUser>();
        page.setList(list);
        page.setPageNum(sch.getPageIndex()); // 设置当前页数
        page.setPageSize(sch.getPageSize()); // 设置每页的数量
        page.setSize(list.size()); // 设置当前页的数量
        page.setPages((int) ((total + sch.getPageSize() - 1) / sch.getPageSize())); // 设置总的页数
        page.setTotal(total); // 设置总的数量

        return page;
    }

    @Override
    public WxUser getByOpenId(String openId) {
        ExpressionQuery query = new ExpressionQuery();
        query.addValueExpression(new ValueExpression("openid", openId));

        List<WxUser> wxUserList = find(query);

        if (CollectionUtils.isNotEmpty(wxUserList)) {
            return wxUserList.get(0);
        }

        return null;
    }

    @Override
    public WxUser getByUserName(String userName) {
        ExpressionQuery query = new ExpressionQuery();
        query.addValueExpression(new ValueExpression("nickname", userName));

        List<WxUser> wxUserList = find(query);

        if (CollectionUtils.isNotEmpty(wxUserList)) {
            return wxUserList.get(0);
        }

        return null;
    }
}